<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="用户ID" prop="userId">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.userId"-->
      <!--            placeholder="请输入用户ID"-->
      <!--            clearable-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="外文名称" prop="name1">
        <el-input
            v-model="queryParams.name1"
            placeholder="请输入外文名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="中文名称" prop="name2">
        <el-input
            v-model="queryParams.name2"
            placeholder="请输入中文名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
          <el-option
              v-for="dict in detail_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="第几集" prop="toThis">
        <el-input
            v-model="queryParams.toThis"
            placeholder="请输入看到第几集"
            clearable
            @keyup.enter="handleQuery"
            type="number"
        />
      </el-form-item>
      <!--      <el-form-item label="有几集" prop="have">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.have"-->
      <!--            placeholder="请输入有几集"-->
      <!--            clearable-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="第几季" prop="season">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.season"-->
      <!--            placeholder="请输入第几季"-->
      <!--            clearable-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="最近观看" style="width: 308px">
        <el-date-picker
            v-model="daterangeToTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
              v-for="dict in detail_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="平台" prop="vendor">-->
      <!--        <el-select v-model="queryParams.vendor" placeholder="请选择平台" clearable>-->
      <!--          <el-option-->
      <!--              v-for="dict in detail_vendor"-->
      <!--              :key="dict.value"-->
      <!--              :label="dict.label"-->
      <!--              :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="重新回顾" style="width: 308px">
        <el-date-picker
            v-model="daterangeReTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

<!--    <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">-->
<!--      <el-table-column type="selection" width="55" align="center"/>-->
<!--      &lt;!&ndash;      <el-table-column label="ID" align="center" prop="id" />&ndash;&gt;-->
<!--      &lt;!&ndash;      <el-table-column label="用户ID" align="center" prop="userId" />&ndash;&gt;-->
<!--      <el-table-column label="外文名称" align="center" prop="name1">-->
<!--        <template #default="scope">-->
<!--          {{ scope.row.name1 }}-->
<!--          <span v-if="scope.row.season">{{ '[S' + scope.row.season + ']' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="中文名称" align="center" prop="name2">-->
<!--        <template #default="scope">-->
<!--          {{ scope.row.name2 }}-->
<!--          <span v-if="scope.row.season">{{ '[' + scope.row.season + '季]' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      &lt;!&ndash;      <el-table-column label="详情" align="center" prop="detail" />&ndash;&gt;-->
<!--      <el-table-column label="类型" align="center" prop="type">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="detail_type" :value="scope.row.type"/>-->
<!--        </template>-->
<!--      </el-table-column>-->

<!--      <el-table-column label="状态" align="center" prop="status">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="detail_status" :value="scope.row.status"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="链接" align="center" prop="url">-->
<!--        <template #default="scope">-->
<!--          <div v-for="(url, index) in jsonParse(scope.row.url)" :key="index">-->
<!--            <el-button @click="openUrl(url.url)">{{ url.name }}</el-button>-->
<!--          </div>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--     <el-table-column label="库链接" align="center" >-->
<!--        <template #default="scope">-->
<!--          <div v-for="(url, index) in jsonParse(getListDataByType(scope.row).url)" :key="index">-->
<!--            <el-button @click="openUrl(url.url)">{{ url.name }}</el-button>-->
<!--          </div>-->
<!--        </template>-->
<!--      </el-table-column>-->

<!--      <el-table-column label="对应的类别ID" align="center" prop="typeId"/>-->
<!--      <el-table-column label="最近观看时间" align="center" prop="toTime" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.toTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="到第几集" align="center" prop="toThis"/>-->


<!--      <el-table-column label="有几集" align="center" prop="have">-->
<!--        <template #default="scope">-->
<!--          <span v-if="scope.row.type > 10 && scope.row.typeId !== 0">-->
<!--            {{getListDataByType(scope.row).have === 0 || getListDataByType(scope.row).have === null ? '未知' : getListDataByType(scope.row).have }}-->
<!--          </span>-->
<!--          <span v-else>-->
<!--          <span v-if="scope.row.have === 0">未知</span>-->
<!--          <span v-else>{{ scope.row.have }}</span>-->
<!--          </span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="第几季" align="center" prop="season">-->
<!--        <template #default="scope">-->
<!--          <span v-if="scope.row.type > 10 && scope.row.typeId !== 0">-->
<!--            {{getListDataByType(scope.row).season === 0 || getListDataByType(scope.row).season === [] ? '未知' : getListDataByType(scope.row).season }}-->
<!--          </span>-->
<!--          <span v-else>-->
<!--          <span v-if="scope.row.season === 0">未知</span>-->
<!--          <span v-else>{{ scope.row.season }}</span>-->
<!--          </span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="更新时间" align="center" prop="renew">-->
<!--        <template #default="scope">-->
<!--          <span v-if="scope.row.type > 10 && scope.row.typeId !== 0">-->
<!--            <div v-for="(time, index) in jsonParse(getListDataByType(scope.row).renew)" :key="index">-->
<!--            {{ weekdays[time.day] }} <br/> {{ time.clock }}-->
<!--          </div>-->
<!--          </span>-->
<!--          <span v-else>-->
<!--          <div v-for="(time, index) in jsonParse(scope.row.renew)" :key="index">-->
<!--            {{ weekdays[time.day] }} <br/> {{ time.clock }}-->
<!--          </div>-->
<!--          </span>-->
<!--        </template>-->
<!--      </el-table-column>-->



<!--      <el-table-column label="图片" align="center" prop="picture" width="100" v-if="isImageUpload">-->
<!--        <template #default="scope">-->
<!--          <span v-if="scope.row.type > 10 && scope.row.typeId !== 0 && scope.row.picture===null">-->
<!--             <image-preview :src="getListDataByType(scope.row).picture" :width="50" :height="50" preview-teleported/>-->
<!--          </span>-->
<!--          <span v-else>-->
<!--            <image-preview :src="scope.row.picture" :width="50" :height="50" preview-teleported/>-->
<!--          </span>-->
<!--        </template>-->
<!--      </el-table-column>-->

<!--      <el-table-column label="图片地址" align="center" prop="pictureUrl" v-if="isImageURL">-->
<!--        <template #default="scope">-->
<!--          <span v-if="scope.row.type > 10 && scope.row.typeId !== 0 && scope.row.pictureUrl===null">-->
<!--            <image-preview :src="getListDataByType(scope.row).pictureUrl" :width="100" :height="100" preview-teleported/>-->
<!--          </span>-->
<!--          <span v-else>-->
<!--          <image-preview :src="scope.row.pictureUrl" :width="100" :height="100" preview-teleported/>-->
<!--          </span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="重看时间" align="center" prop="reTime" width="180">-->
<!--        <template #default="scope">-->
<!--          <span >{{ scope.row.status === 3 || scope.row.status ==='3' ? parseTime(scope.row.reTime, '{y}-{m}-{d} {h}:{i}:{s}') : ''}}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="平台" align="center" prop="vendor">-->
<!--        <template #default="scope">-->
<!--            <span v-if="scope.row.type > 10 && scope.row.typeId !== 0">-->
<!--              <dict-tag :options="getVendorByType(scope.row)" :value="getListDataByType(scope.row).vendor"/>-->
<!--          </span>-->
<!--          <span v-else>-->
<!--            <dict-tag :options="detail_vendor" :value="scope.row.vendor"/>-->
<!--          </span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="简介" align="center" prop="detail" width="400">-->
<!--        <template #default="scope">-->
<!--          <span v-if="scope.row.type > 10 && scope.row.typeId !== 0">-->
<!--            {{getListDataByType(scope.row).detail === null ? '' : getListDataByType(scope.row).detail }}-->
<!--          </span>-->
<!--          <span v-else>-->
<!--            {{ scope.row.detail === null ? '' : scope.row.detail }}-->
<!--          </span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="备注" align="center" prop="remark" width="200"/>-->
<!--    </el-table>-->

    <el-row :gutter="20">
      <el-col :span="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="item in detailList" :key="item.id" >
        <el-card shadow="hover" style="margin-bottom: 20px;">
          <div slot="header" style="text-align: center">
            <span style="font-size: 20px;font-weight: bold">{{ item.name2 + ((item.season === 0 || item.season ===1 || item.season === null) ? '' : '[第' + item.season + '季]')}}</span>
            <p>{{item.name1 === null? '' : item.name1  +((item.season === 0 || item.season ===1 || item.season === null) ? '' : '-[S' + item.season + ']')}}</p>
          </div>

          <div style="text-align: center;">
            <span v-if="item.type > 10 && item.typeId !== 0" :key="index" v-for="(oItem,index) in getListOneDataByType(item)">
              <image-preview :src="getPicUrlByType(item)" :width="100" :height="100" preview-teleported/>
              <p>{{ (getHaveByType(item) !== false) ? '有'+getHaveByType(item)+'集' : ''  }} </p>
              <p>{{ item.toThis !== 0 ? '到'+item.toThis+'集' : ''  }} </p>
              <el-button-group style="margin-bottom: 10px;" v-if="jsonParseByType(oItem).length >0">
                  <el-button v-for="(url, index) in jsonParseByType(oItem)" :key="index" @click="openUrl(url.url)">
                    {{ url.name }}
                  </el-button><br/>
              </el-button-group><br/>
              <dict-tag :options="getVendorByType(item)" :value="getVendorValue(oItem)" style="display: inline"/>
              <dict-tag :options="getStatusByType(item)" :value="getStatusValue(oItem)" style="display: inline"/>
              <p v-for="(time, index) in jsonParseReNew(oItem)" :key="index" v-if="getStatusValue(oItem) !== 0">
                {{ weekdays[time.day] }} <nbsp/> {{ time.clock }} <br/>
              </p>
            </span>
            <span v-else>
              <image-preview v-if="item.picture || item.pictureUrl" :src="item.picture ? item.picture : item.pictureUrl" width="100" height="100" preview-teleported/>
              <p>{{ (item.have || item.have > 0) ? '有'+item.have+'集' : ''  }} </p>
              <p>{{ item.toThis !== 0 ? '到'+item.toThis+'集' : ''  }} </p>
              <el-button-group style="margin-bottom: 10px;" v-if="jsonParseByType(item) > 0">
                  <el-button v-for="(url, index) in jsonParseByType(item)" :key="index" @click="openUrl(url.url)">
                    {{ url.name }}
                  </el-button><br/>
              </el-button-group>
              <dict-tag :options="detail_vendor" :value="item.vendor"/>
              <p v-for="(time, index) in jsonParse(item.renew)" :key="index" v-if="item.renew !== '[{}]' && item.renew.length !== 4">
                {{ weekdays[time.day] }} <nbsp/> {{ time.clock }} <br/>
              </p>
            </span><br v-if="item.status === 1 && item.toTime" />
            {{item.status === 1 ? '观看时间：' + parseTime(item.toTime, '{y}-{m}-{d} {h}:{i}:{s}') : ''}}
            <br v-if="item.status === 3 && item.reTime" />
            {{item.status === 3 ? '重看时间：' + parseTime(item.reTime, '{y}-{m}-{d} {h}:{i}:{s}') : ''}}
            <br v-if="item.remark !==null" />
            {{item.remark === null ? '' : item.remark }}

          </div>
        </el-card>

      </el-col>
    </el-row>


    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    </div>
</template>

<script setup name="Detail">
import {listDetail, getDetail, delDetail, addDetail, updateDetail} from "@/api/detail/detail";
import store from '@/store'
import {getConfigKey} from "@/api/system/config";
import {getListWithOutDetail} from "@/api/utils";
import {computed, onMounted, watch} from "vue";
// import {listAnimation} from "@/api/type/animation";
// import {listBook} from "@/api/type/book";
// import {listCaricature} from "@/api/type/caricature";
// import {listDocumentary} from "@/api/type/documentary";
// import {listMovie} from "@/api/type/movie";
// import {listTeleplay} from "@/api/type/teleplay";


const userId = store.state.value.user.userId

const {proxy} = getCurrentInstance();
const {detail_vendor, detail_type, detail_status} = proxy.useDict('detail_vendor', 'detail_type', 'detail_status');
const {animation_vendor, animation_status} = proxy.useDict('animation_vendor', 'animation_status');
const {book_vendor, book_status} = proxy.useDict('book_vendor', 'book_status');
const {caricature_vendor, caricature_status} = proxy.useDict('caricature_vendor', 'caricature_status');
const {documentary_vendor, documentary_status} = proxy.useDict('documentary_vendor', 'documentary_status');
const {movie_vendor, movie_status} = proxy.useDict('movie_vendor', 'movie_status');
const {teleplay_status, teleplay_vendor} = proxy.useDict('teleplay_status', 'teleplay_vendor');

const animationList = ref([]);
const bookList = ref([]);
const caricatureList = ref([]);
const documentaryList = ref([]);
const movieList = ref([]);
const teleplayList = ref([]);

const detailList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeToTime = ref([]);
const daterangeReTime = ref([]);
const activeTab = ref('basicInfo'); // 默认激活的标签页
const isImageUpload = ref(false); //是否允许上传图片
const isImageURL = ref(false);  //是否允许输入图片地址
const useEditList = ref([]); //正在编辑的列表
getConfigKey("info.image.upload").then(res => {
  isImageUpload.value = res.msg === 'true';
})
getConfigKey("info.image.url").then(res => {
  isImageURL.value = res.msg === 'true';
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: userId,
    name1: null,
    name2: null,
    detail: null,
    type: null,
    typeId: null,
    toThis: null,
    have: null,
    season: null,
    toTime: null,
    status: null,
    vendor: null,
    reTime: null,
  },
  rules: {
    type: [
      {required: true, message: "类型不能为空", trigger: "change"}
    ],
    toThis: [
      {required: true, message: "第几集不能为空", trigger: "blur"}
    ],
    // have: [
    //   {required: true, message: "有几集不能为空", trigger: "blur"}
    // ],
    // season: [
    //   {required: true, message: "第几季不能为空", trigger: "blur"}
    // ],
    toTime: [
      {required: true, message: "最近观看时间不能为空", trigger: "blur"}
    ],
    name2: [
      {required: true, message: "中文名称不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "状态不能为空", trigger: "change"}
    ],
    typeId: [
      {
        validator: (rule, value) => {
          if (form.value.type > 10 && value === 0) {
            return '当 type > 10 时 typeId 不能为 0';
          } else {
            return true; // 返回 true 表示验证通过
          }
        },
        message: '当 type > 10 时 typeId 不能为 0',
        trigger: 'blur'
      }
    ],
    season: [
      {required: true, message: "第几季不能为空", trigger: "blur"}
    ],

  }
});

const {queryParams, form, rules} = toRefs(data);


// 周几的键值对
const weekdays = {
  1: "周一",
  2: "周二",
  3: "周三",
  4: "周四",
  5: "周五",
  6: "周六",
  7: "周日"
};

// type对应的选择列表
const selectListOption = [
  {value: 11, label: 'animationList',vendor: animation_vendor,status: animation_status},
  {value: 21, label: 'teleplayList',vendor: teleplay_vendor,status: teleplay_status},
  {value: 31, label: 'documentaryList',vendor: documentary_vendor,status: documentary_status},
  {value: 41, label: 'movieList',vendor: movie_vendor,status: movie_status},
  {value: 51, label: 'caricatureList',vendor: caricature_vendor,status: caricature_status},
  {value: 61, label: 'bookList',vendor: book_vendor,status: book_status}
];


/** 查询明细列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeToTime && '' != daterangeToTime) {
    queryParams.value.params["beginToTime"] = daterangeToTime.value[0];
    queryParams.value.params["endToTime"] = daterangeToTime.value[1];
  }
  if (null != daterangeReTime && '' != daterangeReTime) {
    queryParams.value.params["beginReTime"] = daterangeReTime.value[0];
    queryParams.value.params["endReTime"] = daterangeReTime.value[1];
  }
  listDetail(queryParams.value).then(response => {
    detailList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

async function getOtherList() {
  const theList = await getListWithOutDetail()
  animationList.value = theList.animationList;
  bookList.value = theList.bookList;
  caricatureList.value = theList.caricatureList;
  documentaryList.value = theList.documentaryList;
  movieList.value = theList.movieList;
  teleplayList.value = theList.teleplayList;
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: userId,
    name1: null,
    name2: null,
    detail: null,
    type: null,
    typeId: 0,
    toThis: null,
    have: null,
    season: null,
    toTime: null,
    renew: [{}],
    url: [{}],
    status: null,
    vendor: null,
    picture: null,
    pictureUrl: null,
    reTime: null,
    remark: null
  };
  proxy.resetForm("detailRef");
}

// 表单重置
function resetWithOutId() {
  form.value = {
    userId: userId,
    name1: null,
    name2: null,
    detail: null,
    type: null,
    typeId: 0,
    toThis: null,
    have: null,
    season: null,
    toTime: null,
    renew: [],
    url: [],
    status: null,
    vendor: null,
    picture: null,
    pictureUrl: null,
    reTime: null,
    remark: null
  };
  proxy.resetForm("detailRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeToTime.value = [];
  daterangeReTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  activeTab.value = 'basicInfo';
  open.value = true;
  title.value = "添加明细";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  activeTab.value = 'basicInfo';
  const _id = row.id || ids.value
  getDetail(_id).then(response => {
    form.value = response.data;
    open.value = true;
    form.value.renew = JSON.parse(response.data.renew);
    form.value.url = JSON.parse(response.data.url);
    title.value = "修改明细";
  });
}

/** 提交按钮 */
function submitForm() {

  if (form.value.type > 10 && form.value.typeId === 0) {
    // console.log(form.value.typeId,typeof form.value.typeId)
    proxy.$modal.msgError("请选择「库」对应的项目名称");
    return;
  }
  if (form.value.status ===3 && form.value.reTime === null) {
    proxy.$modal.msgError("请选择「重看时间」");
    return;
  }
  proxy.$refs["detailRef"].validate(valid => {
    if (valid) {
      form.value.renew = JSON.stringify(form.value.renew);
      form.value.url = JSON.stringify(form.value.url);
      if (form.value.id != null) {
        updateDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除明细编号为"' + _ids + '"的数据项？').then(function () {
    return delDetail(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('detail/detail/export', {
    ...queryParams.value
  }, `明细导出_${new Date().getTime()}.xlsx`)
}

const addTime = () => {
  // console.log(typeof form.value.renew);
  // 确保 form.renew 是数组
  if (!Array.isArray(form.value.renew)) {
    form.renew = [{}];
  }
  form.value.renew.push({day: '', clock: ''});
  // console.log('New time added:', form.value.renew);
};


// 删除更新时间
const removeTime = (index) => {
  // 确保 form.renew 是数组
  if (!Array.isArray(form.value.renew)) {
    return;
  }
  form.value.renew.splice(index, 1);
};

const addURL = () => {
  // 确保 form.url 是数组
  if (!Array.isArray(form.value.url)) {
    form.url = [{}];
  }
  form.value.url.push({name: '', url: ''});
  // console.log('New url added:', form.value.url);
};


// 删除URL
const removeURL = (index) => {
  if (!Array.isArray(form.value.url)) {
    return;
  }
  form.value.url.splice(index, 1);
};

// 将 JSON 字符串转换为 JSON 对象
function jsonParse(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    // console.error("Failed to parse JSON:", error);
    return [{}];
  }
}

function jsonParseByType(rows) {
  try {
    if (rows.url !== null && rows.url !== '') {
      return JSON.parse(rows.url);
    }
  } catch (error) {
    // console.error("Failed to parse JSON:", error);
    return [{}];
  }
}

function openUrl(url) {
  if (url) {
    window.open(url, '_blank');
  }
}

// 填充
function setFormToOption() {
  const row = useEditList.value.find(item => item.id === form.value.typeId);
  if (row) {
    cache_clear_list();
    // 更新表单的值
    form.value.name1 === null ? form.value.name1 = row.name1 : null;
    form.value.name2 === null ? form.value.name2 = row.name2 : null;
    form.value.status === null ? form.value.status = row.status : null;
    form.value.season === null ? form.value.season = row.season : null;
  }
}

// 清空
function resetWithOutOption() {
  if (form.value.type > 10) {
    cache_clear_list();
    if (form.value.typeId !== 0) {
      form.value.typeId = 0
    }
  }

}

function cache_clear_list() {
  if (form.value.name1 !== null) {
    form.value.name1 = null
  }
  if (form.value.name2 !== null) {
    form.value.name2 = null
  }
  if (form.value.status !== null) {
    form.value.status = null
  }
  if (form.value.toThis !== 0) {
    form.value.toThis = 0
  }
  if (form.value.toTime !== null) {
    form.value.toTime = null
  }
  if (form.value.have !== null) {
    form.value.have = null
  }
  if (form.value.season !== null) {
    form.value.season = null
  }
  if (form.value.vendor !== null) {
    form.value.vendor = null
  }
}

const getListDataByType = (rows) => {
  if (rows.type > 10 && rows.typeId !== 0){
    const selectedOption = selectListOption.find(option => option.value === rows.type);
    if (selectedOption){
      const list = (eval(selectedOption.label).value.find(item => item.id === rows.typeId))
      return list;
    }
  }else {
    return []
  }
};
const getListOneDataByType = (rows) => {
  if (rows.type > 10 && rows.typeId !== 0){
    const selectedOption = selectListOption.find(option => option.value === rows.type);
    if (selectedOption){
      const list = (eval(selectedOption.label).value.find(item => item.id === rows.typeId))
      return {list};
    }
  }else {
    return {}
  }
};

const getPicUrlByType = (rows) => {
  try {
    if (rows.type > 10 && rows.typeId !== 0){
      const selectedOption = selectListOption.find(option => option.value === rows.type);
      if (selectedOption){
        const list = (eval(selectedOption.label).value.find(item => item.id === rows.typeId))
        return list.picture === null ? list.pictureUrl : list.picture;
      }
    }else {
      return ''
    }
  }catch (e) {
    // console.log(e)
  }
};
const getHaveByType = (rows) => {
  try {
    if (rows.type > 10 && rows.typeId !== 0){
      const selectedOption = selectListOption.find(option => option.value === rows.type);
      if (selectedOption){
        const list = (eval(selectedOption.label).value.find(item => item.id === rows.typeId))
        return list.have !== null || list.have !== 0 ? list.have : false;
      }
    }else {
      return false
    }
  }catch (e) {
    // console.log(e)
  }
};
const getVendorByType = (rows) => {
  try {
    if (rows.type > 10 && rows.typeId !== 0){
      const selectedOption = selectListOption.find(option => option.value === rows.type);
      if (selectedOption){
        const list = (eval(selectedOption.vendor).value)
        return list;
      }
    }else {
      return []
    }
  }catch (e) {
    
  }

}
const getVendorValue = (oItem) =>{
  try {
    return oItem.vendor !== null ? oItem.vendor : 0;
  }catch (e) {
    // console.log(e)
    return 0
  }
}
const getStatusByType = (rows) => {
  try {
    if (rows.type > 10 && rows.typeId !== 0){
      const selectedOption = selectListOption.find(option => option.value === rows.type);
      if (selectedOption){
        const list = (eval(selectedOption.status).value)
        return list;
      }
    }else {
      return []
    }
  }catch (e) {

  }

}
const getStatusValue = (oItem) =>{
  try {
    return oItem.status !== null ? oItem.status : 0;
  }catch (e) {
    // console.log(e)
    return 0
  }
}
const jsonParseReNew = (oItem) =>{
  try {
    return oItem.renew !== null ? JSON.parse(oItem.renew) : [];
  }catch (e) {
    // console.log(e)
    return []
  }
}
// 监听表单的
watch((form), (newValue, oldValue) => {
  const selectedOption = selectListOption.find(option => option.value === form.value.type);
  // 如果在列表里面找到了对应的选项，则将对应的列表赋值给
  if (selectedOption) {
    useEditList.value = eval(selectedOption.label).value;
    // const row = useEditList.value.find(item => item.id === form.value.typeId);
    // if (row) {
    //   // 更新表单的值
    //   form.value.name1 === null ? form.value.name1 = row.name1 : null;
    //   form.value.name2 === null ? form.value.name2 = row.name2 : null;
    //   form.value.status === null ? form.value.status = row.status : null;
    //   form.value.detail = null;
    //   form.value.have = null;
    //   form.value.season = null;
    //   form.value.vendor = null;
    // }
  } else {
    // 如果没有找到对应的选项，则重置表单
    useEditList.value = [];
    // resetWithOutOption();
  }
}, {deep: true, immediate: true});


onMounted(() => {
  getList();
  getOtherList();
})


</script>


<style scoped>
.el-row {
  display: flex;
  flex-wrap: wrap;
  margin: -10px; /* 使用负边距来抵消子元素的边距，防止换行 */
}
.el-col {
  width: 25%; /* 每个卡片占25%的宽度，这意味着一行可以显示4个 */
  padding: 10px; /* 使用边距来确保卡片之间有间距 */
}
.el-card {
  width: 100%;
}

</style>